import { createAsyncThunk, createSlice, nanoid } from "@reduxjs/toolkit";
import axios from 'axios'

// 直接在action中派发dispatch
export const fetchData = createAsyncThunk('fetch/detailData',async(payload,store) =>{
  console.log(payload,store)
  const res = await axios('http://codercba.com:1888/airbnb/api/home/goodprice')
  store.dispatch(changeList(res.data.list))
})

// 通过extraReducers，派发
export const fetchData2 = createAsyncThunk('fetch/detailData2',async(payload,store) =>{
  console.log(payload,store)
  store.AbortController.signal('ces')
  const res = await axios('http://codercba.com:1888/airbnb/api/home/goodprice')
  return res.data
})

const detailReducer = createSlice({
  name:'detail',
  initialState:{
    detailTitle:'I am detail!',
    detailInfo:[],
    list:[]
  },
  reducers:{
    changeDetailInfoAction(state){
      state.detailInfo = [{id:nanoid(),text:'hahha'}]
    },
    changeList(state,{payload}){
      state.list = payload
      // return { ...state,list:payload}
    }
  },
  extraReducers(builder){
    builder.addCase(fetchData2.pending,(state,action) =>{
      console.log('pending:',state,action)
    }).addCase(fetchData2.fulfilled,(state,action) =>{
      console.log('fulfilled:',state,action)
      state.list = action.payload.list
      // return action.payload.list
    }).addCase(fetchData2.rejected,(state,action) =>{
      console.log('rejected:',state,action)
    })
  }
})

export const { changeDetailInfoAction,changeList } = detailReducer.actions
export default detailReducer.reducer